using System.Collections.Generic;
using Core;
using UnityEngine;

namespace LST_Test
{
    /// <summary>
    /// 测试寻路及其可视化
    /// </summary>
    public class TestAStarSearch : MonoBehaviour
    {
        [SerializeField] public int X;
        [SerializeField] public int Y;
        [SerializeField] public GameObject cylinder;
        [SerializeField] public GameObject cylinder2;
        [SerializeField] public GameObject cylinder3;

        private SquareGrid map;
        private AStarSearch astar;
        private List<GameObject> path = new();
        private HashSet<Node> containePath = new();

        public void CreateAStarGrid(CreateGrid tgt)
        {
            map = new SquareGrid(CreateGrid.Width, CreateGrid.Height);
            astar = new AStarSearch(map);
        }

        public void StartTrace()
        {
            for (int i = 0; i < path.Count; i++)
            {
                GameObject.DestroyImmediate(path[i]);
            }

            path.Clear();
            containePath.Clear();
            var goal = map.GetNode(X, Y);
            var start = map.GetNode(0, 0);
            astar.Search(start, goal, map.DefaultCost);
            var cur = goal;
            while (astar.CameFrom[cur] != null && cur != start)
            {
                var node = astar.CameFrom[cur];
                var instance = GameObject.Instantiate(cylinder, transform, true);
                instance.transform.position = new Vector3(node.X, 1, node.Y);
                path.Add(instance);
                containePath.Add(node);
                cur = astar.CameFrom[cur];
            }

            var iter = astar.CostSoFar.GetEnumerator();
            while (iter.MoveNext())
            {
                if (containePath.Contains(iter.Current.Key) == false)
                {
                    var instance = GameObject.Instantiate(cylinder2, transform, true);
                    instance.transform.position = new Vector3(iter.Current.Key.X, 1, iter.Current.Key.Y);
                    path.Add(instance);
                }
            }

            log.d($"lst - optmPath.count:{astar.OptmPath.Count}");
            for (int i = 0; i < astar.OptmPath.Count; i++)
            {
                var node = astar.OptmPath[i];
                var instance = GameObject.Instantiate(cylinder3, transform, true);
                instance.transform.position = new Vector3(node.X, 2, node.Y);
                path.Add(instance);
            }
        }
    }
}
